// 订单列表的schema
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const orderSchema = new Schema({
    id: { uqique: true, type: String },
    amount: Number,
    create_date: { type: Date, default: Date.now() },
    update_date: { type: Date, default: Date.now() },
    buyer: String,
    mobile: String,
    status: Number, //订单状态 1：进行中 2：已完成 3：已取消
    address: String
}, {
        collections: 'Order'
    })
//公共的counter集合
const CounterSchema = new Schema({
    _id: { type: String, required: true },
    seq: { type: Number, default: 0 }
});

const Counter = mongoose.model('counter', CounterSchema);

orderSchema.pre('save', function (next) {
    let doc = this;
    Counter.findByIdAndUpdate({ _id: 'orderCount' }, { $inc: { seq: 1 } }, { new: true, upsert: true }, function (error, counter) {
        if (error)
            return next(error);
        doc.id = counter.seq;
        next();
    });
});
// 发布
mongoose.model('Order', orderSchema)